package ru.averta.notes.service.impl;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ru.averta.notes.dao.UserDao;
import ru.averta.notes.domain.User;
import ru.averta.notes.exceptions.UserAlreadyExistsException;
import ru.averta.notes.service.UserService;
import ru.averta.notes.service.security.login.UserPasswordEncoder;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    
    Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    public void createUser(User user) throws UserAlreadyExistsException {
        User testUser = findUserByMail(user.getMail());
        if (testUser != null) {
            logger.debug("Найден пользователь с почтовым ящиком " + user.getMail() + " - " + testUser);
            throw new UserAlreadyExistsException("User " + user.getMail() + " already exists");
        }

        user.setPassword(UserPasswordEncoder.hashPassword(user.getPassword()));
        userDao.create(user);
    }

    @Transactional(readOnly=true)
    public User findUserByMail(String mail) {
        return userDao.findUserByMail(mail.toLowerCase());
    }
}
